package com.study.oauth2demo.handler;

import com.study.oauth2demo.entity.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

/**
 * 请求和响应拦截器
 */
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();

        Set<String> uri = new HashSet<>();
        uri.add("/r1");
        uri.add("/r2");
        // 只拦截固定的请求
        if (!uri.contains(requestURI)){
            return true;
        }

        Object object = request.getSession().getAttribute(UserDto.SESSION_KEY);
        UserDto userDto = (UserDto)object;
        if (userDto == null){
            writeContent(response, "请登录认证");
        }
        assert userDto != null;
        if(userDto.getAuthorities().contains("p1") && requestURI.equals("/r1")){
            return true;
        }
        if(userDto.getAuthorities().contains("p2") && requestURI.equals("/r2")){
            return true;
        }
        writeContent(response, "没有权限拒绝访问");
        return false;
    }

    /**
     * 写信息到返回的响应中
     * @param response
     * @param msg
     * @throws IOException
     */
    private void writeContent(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(msg);
        writer.close();
    }
}
